package com.by.course.serivce.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.by.course.entity.base.BaseResult;
import com.by.course.entity.bo.*;
import com.by.course.entity.vo.lessonreview.req.AddBaseLessonReviewVO;
import com.by.course.entity.vo.lessonreview.req.DeleteBaseLessonReviewVO;
import com.by.course.entity.vo.lessonreview.req.GetBaseLessonReviewVO;
import com.by.course.entity.vo.lessonreview.req.UpdateBaseLessonReviewVO;
import com.by.course.entity.vo.lessonreview.resp.BaseLessonReviewResultVO;
import com.by.course.enums.ErrEnum;
import com.by.course.execption.BusinessException;
import com.by.course.mapper.*;
import com.by.course.serivce.BaseLessonReviewService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
public class BaseLessonReviewServiceImpl extends ServiceImpl<BaseLessonReviewMapper, BaseLessonReview> implements BaseLessonReviewService {

    @Resource
    private BaseLessonReviewMapper baseLessonReviewMapper;

    @Resource
    private BaseLessonMapper baseLessonMapper;

    @Resource
    private BaseLessonReviewService baseLessonReviewService;

    @Resource
    private BaseAppointmentMapper baseAppointmentMapper;

    @Resource
    private BaseScheduleMapper baseScheduleMapper;

    @Resource
    private BaseCourseMapper baseCourseMapper;

    @Resource
    private BaseUserBindMapper baseUserBindMapper;

    @Override
    public BaseResult<List<BaseLessonReviewResultVO>> queryLessonReview(GetBaseLessonReviewVO vo) {
        if (vo.getPageSize() == null) {
            vo.setPageSize(10);
        }
        if (vo.getCurrentPage() == null) {
            vo.setCurrentPage(1);
        }
        vo.setOffset((vo.getCurrentPage() - 1) * vo.getPageSize());
        if (vo.getUserId() == null) {
            throw new BusinessException("用户id不能为空", ErrEnum.REVIEW_ERR.getCode());
        }

        List<BaseLessonReview> baseLessonReviewList = baseLessonReviewMapper.selectByUserId(vo.getUserId());
        if (baseLessonReviewList == null || baseLessonReviewList.isEmpty()) {
            return new BaseResult.Builder<List<BaseLessonReviewResultVO>>().setData(null).build();
        }

        List<Long> baseAppointmentIdList = baseLessonReviewList.stream().map(BaseLessonReview::getBaseAppointmentId).collect(Collectors.toList());
        List<BaseAppointment> baseAppointmentList = baseAppointmentMapper.selectBatchIds(baseAppointmentIdList);
        if (baseAppointmentList == null || baseAppointmentList.isEmpty()) {
            return new BaseResult.Builder<List<BaseLessonReviewResultVO>>().setData(null).build();
        }

        // 将baseAppointmentList转换为map，key为id，value为BaseAppointment对象
        Map<Long, BaseAppointment> baseAppointmentMap = baseAppointmentList.stream().collect(Collectors.toMap(BaseAppointment::getId, Function.identity()));

        List<Long> scheduleIdList = baseAppointmentList.stream().map(BaseAppointment::getScheduleId).collect(Collectors.toList());
        List<BaseSchedule> baseScheduleList = baseScheduleMapper.selectBatchIds(scheduleIdList);
        if (baseScheduleList == null || baseScheduleList.isEmpty()) {
            return new BaseResult.Builder<List<BaseLessonReviewResultVO>>().setData(null).build();
        }
        Map<Long, BaseSchedule> baseScheduleMap = baseScheduleList.stream().collect(Collectors.toMap(BaseSchedule::getId, Function.identity()));

        List<Long> lessonIdList = baseScheduleList.stream().map(BaseSchedule::getLessonId).collect(Collectors.toList());
        List<BaseLesson> baseLessonList = baseLessonMapper.selectBatchIds(lessonIdList);
        if (baseLessonList == null || baseLessonList.isEmpty()) {
            return new BaseResult.Builder<List<BaseLessonReviewResultVO>>().setData(null).build();
        }
        Map<Long, BaseLesson> baseLessonMap = baseLessonList.stream().collect(Collectors.toMap(BaseLesson::getId, Function.identity()));

        List<Long> courseIdList = baseLessonList.stream().map(BaseLesson::getCourseId).collect(Collectors.toList());
        List<BaseCourse> baseCourseList = baseCourseMapper.selectBatchIds(courseIdList);
        if (baseCourseList == null || baseCourseList.isEmpty()) {
            return new BaseResult.Builder<List<BaseLessonReviewResultVO>>().setData(null).build();
        }
        Map<Long, BaseCourse> baseCourseMap = baseCourseList.stream().collect(Collectors.toMap(BaseCourse::getId, Function.identity()));

        List<BaseLessonReviewResultVO> result = new ArrayList<>(baseLessonReviewList.size());

        for (BaseLessonReview baseLessonReview : baseLessonReviewList) {
            BaseLessonReviewResultVO baseLessonReviewResultVO = new BaseLessonReviewResultVO();
            BeanUtil.copyProperties(baseLessonReview, baseLessonReviewResultVO);
            if (baseLessonReview.getImgUrl() != null) {
                String[] imgUrlList = baseLessonReview.getImgUrl().split(",");
                baseLessonReviewResultVO.setImgUrlList(Arrays.stream(imgUrlList).collect(Collectors.toList()));
            }
            if (baseAppointmentMap.containsKey(baseLessonReview.getBaseAppointmentId())) {
                BaseAppointment baseAppointment = baseAppointmentMap.get(baseLessonReview.getBaseAppointmentId());
                if (baseScheduleMap.containsKey(baseAppointment.getScheduleId())) {
                    BaseSchedule baseSchedule = baseScheduleMap.get(baseAppointment.getScheduleId());
                    baseLessonReviewResultVO.setStartTime(baseSchedule.getStartTime());
                    baseLessonReviewResultVO.setEndTime(baseSchedule.getEndTime());

                    if (baseLessonMap.containsKey(baseSchedule.getLessonId())) {
                        BaseLesson baseLesson = baseLessonMap.get(baseSchedule.getLessonId());
                        if (baseCourseMap.containsKey(baseLesson.getCourseId())) {
                            BaseCourse baseCourse = baseCourseMap.get(baseLesson.getCourseId());
                            baseLessonReviewResultVO.setCourseName(baseCourse.getName());
                        }
                        baseLessonReviewResultVO.setLessonTitle(baseLesson.getTitle());
                    }
                }
            }
            result.add(baseLessonReviewResultVO);
        }

        return new BaseResult.Builder<List<BaseLessonReviewResultVO>>().setData(result).build();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult<String> createEvaluate(AddBaseLessonReviewVO vo) {
        if (vo.getUserId() == null || vo.getBaseAppointmentId() == null) {
            throw new BusinessException("评价的相关参数不能为空", ErrEnum.REVIEW_ERR.getCode());
        }
        BaseLessonReview lessonView = new BaseLessonReview();
        BeanUtil.copyProperties(vo, lessonView);

        if (vo.getImgUrlList() != null && !vo.getImgUrlList().isEmpty()) {
            String imgUrl = String.join(",", vo.getImgUrlList());
            lessonView.setImgUrl(imgUrl);
        }

        baseLessonReviewMapper.insertSelective(lessonView);

        baseAppointmentMapper.updateStatus(vo.getBaseAppointmentId(), 5);

        return new BaseResult.Builder<String>().build();
    }

    @Override
    public BaseResult<String> updateEvaluate(UpdateBaseLessonReviewVO vo) {
        if (vo.getId() == null) {
            throw new BusinessException("评价的相关参数不能为空", ErrEnum.REVIEW_ERR.getCode());
        }
        BaseLessonReview baseLessonReview = baseLessonReviewMapper.selectById(vo.getId());
        if (StrUtil.isNotBlank(vo.getComment())) {
            baseLessonReview.setComment(vo.getComment());
        }
        if (StrUtil.isNotBlank(vo.getContent())) {
            baseLessonReview.setContent(vo.getContent());
        }
        if (vo.getImgUrlList() != null && !vo.getImgUrlList().isEmpty()) {
            String imgUrl = String.join(",", vo.getImgUrlList());
            baseLessonReview.setImgUrl(imgUrl);
        }
        if (vo.getRating() != null) {
            baseLessonReview.setRating(vo.getRating());
        }

        baseLessonReviewMapper.updateByPrimaryKeySelective(baseLessonReview);
        return new BaseResult.Builder<String>().build();
    }

    @Override
    public BaseResult<String> deleteEvaluate(DeleteBaseLessonReviewVO vo) {
        if (vo.getId() == null) {
            throw new BusinessException("评价的相关参数不能为空", ErrEnum.REVIEW_ERR.getCode());
        }
        BaseLessonReview baseLessonReview = baseLessonReviewMapper.selectById(vo.getId());
        if (baseLessonReview == null) {
            throw new BusinessException("评价的相关参数不能为空", ErrEnum.REVIEW_ERR.getCode());
        }
        baseLessonReviewMapper.deleteById(baseLessonReview.getId());
        return new BaseResult.Builder<String>().build();
    }

    @Override
    public BaseResult<BaseLessonReviewResultVO> getEvaluateByTeacher(GetBaseLessonReviewVO vo) {
        if (vo.getId() == null) {
            throw new BusinessException("评价的相关参数不能为空", ErrEnum.REVIEW_ERR.getCode());
        }
        BaseLessonReview baseLessonReview = baseLessonReviewMapper.selectById(vo.getId());
        BaseLessonReviewResultVO baseLessonResultVO = new BaseLessonReviewResultVO();
        BeanUtil.copyProperties(baseLessonReview, baseLessonResultVO);
        if (baseLessonReview.getImgUrl() != null) {
            String[] imgUrlList = baseLessonReview.getImgUrl().split(",");
            baseLessonResultVO.setImgUrlList(Arrays.stream(imgUrlList).collect(Collectors.toList()));
        }
        return new BaseResult.Builder<BaseLessonReviewResultVO>().setData(baseLessonResultVO).build();
    }

    @Override
    public BaseResult<List<BaseLessonReviewResultVO>> listEvaluateByTeacher(GetBaseLessonReviewVO vo) {
        if (vo.getUserId() == null) {
            throw new BusinessException("用户ID不能为空", ErrEnum.REVIEW_ERR.getCode());
        }
        List<BaseLessonReview> baseLessonReviewList = baseLessonReviewMapper.selectByTeacherId(vo.getUserId());
        if (baseLessonReviewList == null || baseLessonReviewList.isEmpty()) {
            return new BaseResult.Builder<List<BaseLessonReviewResultVO>>().setData(null).build();
        }
        List<BaseLessonReviewResultVO> baseLessonReviewResultVoList = new ArrayList<>(baseLessonReviewList.size());
        for (BaseLessonReview baseLessonReview : baseLessonReviewList) {
            BaseLessonReviewResultVO baseLessonResultVO = new BaseLessonReviewResultVO();
            BeanUtil.copyProperties(baseLessonReview, baseLessonResultVO);
            if (baseLessonReview.getImgUrl() != null) {
                String[] imgUrlList = baseLessonReview.getImgUrl().split(",");
                baseLessonResultVO.setImgUrlList(Arrays.stream(imgUrlList).collect(Collectors.toList()));
            }
            baseLessonReviewResultVoList.add(baseLessonResultVO);
        }
        return new BaseResult.Builder<List<BaseLessonReviewResultVO>>().setData(baseLessonReviewResultVoList).build();
    }
}
